document.domain = "cbc.ca";

var Slideshow_FLA = function() {
	
	var galleries_count = 0;
	var on_page = 1;
	var data_loaded = false;

	return {
		assets: [],
		init: function() {
			this.loadAssets(on_page);
		},
		loadAssets: function(onPage) {
			var rb = new RequestBatch();
			var ugp = new UserGalleryPage(new UserKey(), 10, onPage, new MediaType("Photo"));
			rb.AddToRequest(ugp);
			rb.BeginRequest($S.getVal("serverUrl"), this.handleUserAssets);
		},
		handleUserAssets: function(_responseBatch) {
			console.log(_responseBatch);
			galleries_count = parseInt(_responseBatch.Responses[0].UserGalleryPage.NumberOfGalleries);
			on_page = parseInt(_responseBatch.Responses[0].UserGalleryPage.OnPage);
			var pages_count = Math.ceil(galleries_count/10);
			var galleries = _responseBatch.Responses[0].UserGalleryPage.Galleries;
			var assets_length = CBC.APP.Slideshow_FLA.assets.length;

			for (var i=0; i<(galleries.length); i++) {
				var gallery = {};
				gallery.GalleryKey = galleries[i].GalleryKey.Key;
				gallery.Title = galleries[i].Title;
				gallery.Tags = galleries[i].Tags;
				gallery.Description = galleries[i].Description;
				gallery.CreatedOn = galleries[i].CreatedOn;
				
				CBC.APP.Slideshow_FLA.assets.push(gallery);
				CBC.APP.Slideshow_FLA.getUserPhotosFromGalleryKey(galleries[i].GalleryKey.Key,1,i+assets_length);
			}
			if (pages_count != on_page) {
				on_page++;
				CBC.APP.Slideshow_FLA.loadAssets(on_page);
			}
		},

		getUserPhotosFromGalleryKey: function(galleryKey, onPage, _index) {
			var rb = new RequestBatch();
			var pp = new PhotoPage(new GalleryKey(galleryKey), 10, onPage, "TimeStampAscending");
			rb.AddToRequest(pp);
			rb.BeginRequest($S.getVal("serverUrl"), function(_responseBatch) {

				var pp = _responseBatch.Responses[0].PhotoPage;
				var p_count = parseInt(pp.NumberOfPhotos);
				var p_on_page = parseInt(pp.OnPage);
				var p_pages_count = Math.ceil(p_count/10);

				if (!CBC.APP.Slideshow_FLA.assets[_index].Photos) CBC.APP.Slideshow_FLA.assets[_index].Photos = [];

				for (var i=0; i<pp.Photos.length; i++) {
					CBC.APP.Slideshow_FLA.assets[_index].Photos.push(pp.Photos[i]);
				}

				if (p_pages_count != (p_on_page-1)) {
					CBC.APP.Slideshow_FLA.getUserPhotosFromGalleryKey(galleryKey,(p_on_page+1), _index);
				} else {
					if (_index == galleries_count-1) {
						CBC.APP.Slideshow_FLA.end();
						document.getElementById('status').innerHTML = "Done fetching assets.";
					}
				}

			});
		},

		getAssets: function() {
			if (data_loaded) return this.assets; else return false;
		},

		end: function() {
			data_loaded = true;
		}
	};

};
CBC.register({_name:'Slideshow_FLA',_class:Slideshow_FLA,_nameSpace: CBC.APP});